package com.springcloud.alibabanacosconfig.mq.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.springcloud.alibabanacosconfig.mq.dto.MailVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageBuilder;
import org.springframework.amqp.core.MessageDeliveryMode;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.AbstractJavaTypeMapper;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @version V1.0
 * @Author 宋聚智
 * @Date 2019/10/22 17:03
 * @description
 * @Modify By：
 * @ModifyTime： 2019/10/22
 * @Modify marker：
 **/
@RestController
@Slf4j
public class MailController {
    private static final String prefix="mail";
    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    ObjectMapper objectMapper;
    @Autowired
    Environment env;
    @GetMapping(prefix+"/send")
    public String sendMail(){
        rabbitTemplate.setExchange(env.getProperty("mail.exchange.name"));
        rabbitTemplate.setRoutingKey(env.getProperty("mail.routing.key.name"));
        rabbitTemplate.setMessageConverter(new Jackson2JsonMessageConverter());
        MailVo mailvo = MailVo.builder().sender("admin").context("你好").build();
        Message message = null;
        try {
            message = MessageBuilder.withBody(objectMapper.writeValueAsBytes(mailvo)).setDeliveryMode(MessageDeliveryMode.PERSISTENT).build();
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        message.getMessageProperties().setHeader(AbstractJavaTypeMapper.DEFAULT_CONTENT_CLASSID_FIELD_NAME, MessageProperties.CONTENT_TYPE_JSON);
        rabbitTemplate.convertAndSend(message);
        return "OK";
    }
}
